#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include "GEvent.h"
#include "GError.h"

namespace GThread
{
	// Description: Creates an event with given parameters
	// Return: True is successfull, false otherwise.
	// Notes: If an event is created with same name before the created event will be a referance to the previous one
	// -----------------------------------------------------
	bool GEvent::Create(bool ManualReset, bool StartSignaled, const char* Name)
	{
		if (IsCreated())
		{
			return false;
		}

		Event = CreateEvent(NULL, ManualReset, StartSignaled, Name);
		if (Event == NULL)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}

		this->Name = Name == NULL ? "" : Name;
		this->ManualReset = ManualReset;

		return true;
	}

	// Description: Releases the handle.
	// Return:
	// Notes: Does not release the actual event object until referance count of the events drops to zero.
	// -----------------------------------------------------
	void GEvent::Release()
	{
		if (!IsCreated())
		{
			return;
		}
	
		Name = "";
		ManualReset = true;

		CloseHandle(Event);
		Event = NULL;
	}

	// Description: Signals the event.
	// Return: True is successfull, false otherwise.
	// Notes: Gives error if event is not created.
	// -----------------------------------------------------
	bool GEvent::Signal()
	{
		GUtil::GError::DebugCheck(!IsCreated(), "Event is not created.");

		BOOL Result = SetEvent(Event);
		if (Result == 0)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}

		return true;
	}

	// Description: Resets the event.
	// Return: True is successfull, false otherwise.
	// Notes: Evetn must be created.
	// -----------------------------------------------------
	bool GEvent::Reset()
	{
		GUtil::GError::DebugCheck(!IsCreated(), "Event is not created.");

		BOOL Result = ResetEvent(Event);
		if (Result == 0)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}

		return true;
	}

}